<?php
use Logger\Base as Logger;
class ContentServer {
  /*
   * Creates a document component in the SAP content server
   */
  public static function create($data, $content_respository, $document_id, $component_id) {
    if(($content_length = strlen($data)) === 0) {
      return false;
    }
    
    $settings = ContentServer::load_settings();
    //$action = 'create';
    ;
    $uri = ContentServer::build_create_uri($content_respository, $document_id, $component_id, $content_length, $settings);

    // initalize cURL handle.
    $curl = curl_init($uri);
    /*
    // Create memory handle
    $file = fopen('php://memory', 'rw');
    //fwrite($file, $data);
    rewind($file);
    */
    
    $file = tmpfile();
    fwrite($file, $data);
    rewind($file);
    
    
    // specify file to be sent
    curl_setopt($curl, CURLOPT_INFILE, $file);
    // tell cURL the filesize
    curl_setopt($curl, CURLOPT_INFILESIZE, $content_length);
    // set request mode to HTTP-PUT
    curl_setopt($curl, CURLOPT_PUT, 1);
    
    //curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
    //curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    //curl_setopt($curl, CURLOPT_HTTPHEADER, '');
    
    // set cURL verbosity
    curl_setopt($curl, CURLOPT_VERBOSE, 0);
    // tell cURL to get headers.
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // tell cURL to return the result.
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    Logger::logger()->debug("EXECUTING QUERY: {$uri}");
    
    // exec cURL command and get result into $response
    $response = curl_exec($curl);

    // get content-server http response headers
    $response_headers = curl_getinfo($curl);
    
    // get response code from the headers 
    $response_code = (string) $response_headers['http_code'];

    // close cURL session
    curl_close($curl);
    
    // close file handle
    fclose($file);
    
    // if the content-server http response code begins with "2", the request
    // was successful.
    if(substr($response_code, 0, 1) != '2') {
      Logger::logger()->error("Error creating document. Got respose code [{$response_code}]");
      return false;
      //throw new Exception('Content Server request failed! HTTP response code ['.$response_code.'] for URL ['.$uri.']');
    }

    return true;
  }

  /*
   * Reads a document component from the SAP content server
   */
  public static function read($content_respository, $document_id, $component_id) {
    $settings = ContentServer::load_settings();
    //$action = 'get';
    $uri = ContentServer::build_read_uri($content_respository, $document_id, $component_id, $settings);
    //echo $uri;
    
    // initalize cURL handle.
    $curl = curl_init($uri);
    
    // set cURL verbosity
    curl_setopt($curl, CURLOPT_VERBOSE, 0);
    // tell cURL to get headers.
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // tell cURL to return the result.
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    Logger::logger()->debug("EXECUTING QUERY: {$uri}");
    // exec cURL command and get result into $response
    $response = curl_exec($curl);

    // get content-server http response headers
    $response_headers = curl_getinfo($curl);
    
    // get response code from the headers 
    $response_code = (string) $response_headers['http_code'];

    // close cURL session
    curl_close($curl);
    
    // if the content-server http response code begins with "2", the request
    // was successful.
    if(substr($response_code, 0, 1) != '2') {
      Logger::logger()->error('Content Server request failed! HTTP response code ['.$response_code.'] for URL ['.$uri.']');
      return false;
      //throw new Exception('Content Server request failed! HTTP response code ['.$response_code.'] for URL ['.$uri.']');
    }

    return $response;
  }
  
  /*
   * Updates a document component in the SAP content server
   */
  public static function update($data, $content_respository, $document_id, $component_id) {
    $settings = ContentServer::load_settings();
    //$action = 'update';
    $content_length = strlen($data);
    $uri = ContentServer::build_update_uri($content_respository, $document_id, $component_id, $content_length, $settings);
    //echo $uri;
    
    // initalize cURL handle.
    $curl = curl_init($uri);
    /*
    // Create memory handle
    $file = fopen('php://memory', 'rw');
    //fwrite($file, $data);
    rewind($file);
    */
    
    $file = tmpfile();
    fwrite($file, $data);
    rewind($file);
    
    
    // specify file to be sent
    curl_setopt($curl, CURLOPT_INFILE, $file);
    // tell cURL the filesize
    curl_setopt($curl, CURLOPT_INFILESIZE, $content_length);
    // set request mode to HTTP-PUT
    curl_setopt($curl, CURLOPT_PUT, 1);
    
    //curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
    //curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    //curl_setopt($curl, CURLOPT_HTTPHEADER, '');
    
    // set cURL verbosity
    curl_setopt($curl, CURLOPT_VERBOSE, 0);
    // tell cURL to get headers.
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // tell cURL to return the result.
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    Logger::logger()->debug("EXECUTING QUERY: {$uri}");
    // exec cURL command and get result into $response
    $response = curl_exec($curl);

    // get content-server http response headers
    $response_headers = curl_getinfo($curl);
    
    // get response code from the headers 
    $response_code = (string) $response_headers['http_code'];

    // close cURL session
    curl_close($curl);
    
    // close file handle
    fclose($file);
    
    // if the content-server http response code begins with "2", the request
    // was successful.
    if(substr($response_code, 0, 1) != '2') {
      Logger::logger()->error('Content Server request failed! HTTP response code ['.$response_code.'] for URL ['.$uri.']');
      return false;
      //throw new Exception('Content Server request failed! HTTP response code ['.$response_code.'] for URL ['.$uri.']');
    }

    return true;
  }
  
  /*
   * Deletes a document component from the SAP content server
   *
   * If the component_id is set to false, the whole document will be deleted
   */
  public static function delete($content_respository, $document_id, $component_id) {
    $settings = ContentServer::load_settings();
    //$action = 'delete';
    $uri = ContentServer::build_delete_uri($content_respository, $document_id, $component_id, $settings);
    // initalize cURL handle.
    //echo $uri;
    
    $curl = curl_init($uri);
    
    // set cURL verbosity
    curl_setopt($curl, CURLOPT_VERBOSE, 0);
    // tell cURL to get headers.
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // tell cURL to return the result.
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    Logger::logger()->debug("EXECUTING QUERY: {$uri}");
    // exec cURL command and get result into $response
    $response = curl_exec($curl);

    // get content-server http response headers
    $response_headers = curl_getinfo($curl);
    
    // get response code from the headers 
    $response_code = (string) $response_headers['http_code'];

    // close cURL session
    curl_close($curl);
    
    // if the content-server http response code begins with "2", the request
    // was successful.
    if(substr($response_code, 0, 1) != '2') {
      Logger::logger()->error('Content Server request failed! HTTP response code ['.$response_code.'] for URL ['.$uri.']');
      return false;
      //throw new Exception('Content Server request failed! HTTP response code ['.$response_code.'] for URL ['.$uri.']');
    }

    return true;  
  }
  
  /*
   * Loads settings from APP_BASE/config/content_server.ini
   */
  public static function load_settings() {
    if(!($settings = parse_ini_file(APP_BASE.'/config/content_server.ini', true))) {
      throw new Exception('Could not read the ContentServer configuration file. '.
                          'Please make sure that there is a proper content_server.ini file in the '.APP_BASE.'/config folder!');
    }
    $env_settings = $settings[\Roboframe\Base::environment()];
    if(!isset($settings[\Roboframe\Base::environment()])) {
      throw new Exception("Section [".\Roboframe\Base::environment()."] not found in ini-file!");
      
    }
    return $env_settings;  
  }
  
  /*
   * Builds URIs for content server access
   */
  public static function build_create_uri($content_respository, $document_id, $component_id, $content_length, $settings) {
// http://195.203.118.33:1090/ContentServer/ContentServer.dll?create&contRep=Z9&docId=+100000308772&compId=data&Content-Length=40056&pVersion=0046       
    $action = 'create';
    return sprintf('http://%s:%s%s?%s&contRep=%s&docId=%s&compId=%s&Content-Length=%s&pVersion=%s'
                 , $settings['ip_address']
                 , $settings['port']
                 , $settings['dll_path']
                 , $action
                 , $content_respository
                 , $document_id
                 , $component_id
                 , $content_length
                 , $settings['protocol_version']
    );
  } 
  
  /*
   * Builds URIs for content server access
   */
  public static function build_read_uri($content_respository, $document_id, $component_id, $settings) {
    $action = 'get';
    return sprintf('http://%s:%s%s?%s&pVersion=%s&contRep=%s&docId=%s&compId=%s'
                 , $settings['ip_address']
                 , $settings['port']
                 , $settings['dll_path']
                 , $action
                 , $settings['protocol_version']
                 , $content_respository
                 , $document_id
                 , $component_id
    );
  }   
  
  /*
   * Builds URIs for content server access
   */
  public static function build_update_uri($content_respository, $document_id, $component_id, $content_length, $settings) {
// http://195.203.118.33:1090/ContentServer/ContentServer.dll?create&contRep=Z9&docId=+100000308772&compId=data&Content-Length=40056&pVersion=0046       
    $action = 'update';
    return sprintf('http://%s:%s%s?%s&pVersion=%s&contRep=%s&docId=%s&compId=%s&Content-Length=%s'
                 , $settings['ip_address']
                 , $settings['port']
                 , $settings['dll_path']
                 , $action
                 , $settings['protocol_version']
                 , $content_respository
                 , $document_id
                 , $component_id
                 , $content_length
    );
  } 
  
  /*
   * Builds URIs for content server access
   *
   * If the component_id is set to false, the whole document will be deleted
   */
  public static function build_delete_uri($content_respository, $document_id, $component_id, $settings) {
    // http://195.203.118.33:1090/ContentServer/ContentServer.dll?delete&pVersion=0046&contRep=Z9&docId=+100000308772&compId=data       
    $action = 'delete';
    if($component_id === false) {
      return sprintf('http://%s:%s%s?%s&pVersion=%s&contRep=%s&docId=%s'
                   , $settings['ip_address']
                   , $settings['port']
                   , $settings['dll_path']
                   , $action
                   , $settings['protocol_version']
                   , $content_respository
                   , $document_id
      );
    } else {
      return sprintf('http://%s:%s%s?%s&pVersion=%s&contRep=%s&docId=%s&compId=%s'
                   , $settings['ip_address']
                   , $settings['port']
                   , $settings['dll_path']
                   , $action
                   , $settings['protocol_version']
                   , $content_respository
                   , $document_id
                   , $component_id
      );
    }

  }
}
?>